#include <QtCore/QFile>
#include <QtNetwork/QNetworkCookie>

#include "CookieJar.h"

CookieJar::CookieJar(const QString &s, QObject *parent)	: QNetworkCookieJar(parent), path(s)
{
	QFile f(path);
	if (f.open(QIODevice::ReadOnly))
	{
		QList<QNetworkCookie> list;

		while (!f.atEnd())
		{
			QByteArray sizeByteArray = f.read(4);
			if (sizeByteArray.size() != 4)
				break;

			unsigned int size = ((unsigned char)sizeByteArray[0] << 0) | ((unsigned int)sizeByteArray[1] << 8) | ((unsigned int)sizeByteArray[2] << 16) | ((unsigned int)sizeByteArray[3] << 24);
			QByteArray rawCookie = f.read(size);
			if (rawCookie.size() != size)
				break;

			list.append(QNetworkCookie::parseCookies(rawCookie));
		}

		setAllCookies(list);
	}
}

CookieJar::~CookieJar()
{
	QList<QNetworkCookie> cookies = allCookies();
	QFile f(path);
	if (f.open(QIODevice::WriteOnly))
	{
		for (int i = 0; i != cookies.count(); ++i)
		{
			QByteArray cookie = cookies[i].toRawForm();
			unsigned short size = cookie.size();
			QByteArray sizeByteArray;
			sizeByteArray.push_back((unsigned char)(size >> 0));
			sizeByteArray.push_back((unsigned char)(size >> 8));
			sizeByteArray.push_back((unsigned char)(size >> 16));
			sizeByteArray.push_back((unsigned char)(size >> 24));
			f.write(sizeByteArray);
			f.write(cookie, cookie.size());
		}
	}
}

void CookieJar::clear()
{
	setAllCookies(QList<QNetworkCookie>());
}
